package org.i_plus.model.dao;



import java.sql.Blob;

import org.i_plus.model.TarotBean;
import org.i_plus.model.TarotDAO;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TarotDAOHibernate implements TarotDAO{
	private SessionFactory sessionFactory = null;

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	@Override
	public TarotBean selectT(int num){		
		Session session = this.sessionFactory.getCurrentSession();
		return (TarotBean)session.get(TarotBean.class, num);
	}
	@Override
	public void insertT(int num ,String name, byte[] pic ,String content){
		Session session = this.sessionFactory.getCurrentSession();
//		Session session = DefaultFactory.getSessionFactory().openSession();
//		Transaction tx = session.beginTransaction();
		TarotBean bean= new TarotBean();
		bean.setNum(num);
		bean.setName(name);
		bean.setPic(pic);
		bean.setContent(content);
		session.save(bean);
//		tx.commit();
//		session.close();
	}
	@Override
	public void updateT(int num,String name, byte[] pic ,String content){
		Session session = this.sessionFactory.getCurrentSession();
//		Session session = DefaultFactory.getSessionFactory().openSession();
//		Transaction tx = session.beginTransaction();
		TarotBean bean = (TarotBean)session.get(TarotBean.class, num);
		bean.setName(name);
		bean.setPic(pic);
		bean.setContent(content);
		session.saveOrUpdate(bean);
//		tx.commit();
//		session.close();
	}
	@Override
	public void deleteT(int num){
		Session session = this.sessionFactory.getCurrentSession();
//		Session session = DefaultFactory.getSessionFactory().openSession();
//		Transaction tx =session.beginTransaction();
		TarotBean bean = (TarotBean)session.get(TarotBean.class, num);
		session.delete(bean);
//		tx.commit();session.close();
		
	}
	public static void main(String[] args){
		
		ApplicationContext context = new ClassPathXmlApplicationContext("beans.config.xml");
		SessionFactory sessionFactory = (SessionFactory) context.getBean("sessionFactory");
		
		Transaction tx = sessionFactory.getCurrentSession().beginTransaction();
		
		TarotDAOHibernate tdao = (TarotDAOHibernate) context.getBean("tarotDAO");
		TarotBean bean = tdao.selectT(0);
		System.out.println(bean);
//		tdao.insertT(4, "Spade", null, "Sword");
//		tdao.updateT(4, "Gold", null, "Spade");
//		tdao.selectT(4);
//		tdao.deleteT(4);
		tx.commit();
		
//		TarotDAOHibernate tdao = new TarotDAOHibernate();
//		tdao.insertT(3, "Sword", null, "Sword");
//		tdao.selectT(1);
//		tdao.updateT(1, "Gold", null, "Gold");
//		tdao.deleteT(1);
		System.out.println("done");
	}
}
